let scheduler = require('pomelo-scheduler');
let dao = require('../../../dao/commonDao');
let userDao = require('../../../dao/userDao');
let commonDao = require('../../../dao/commonDao');
let pomelo = require('pomelo');
let logger = require('pomelo-logger').getLogger('logic');
let moment = require('moment');
let async = require('async');
//let redis = require('../../../dao/redis/redisClient');

let userInfoServices = require('../../../services/userInfoServices');

let exp = module.exports;

exp.init = function () {


    this.dailyTaskSchedulerID = scheduler.scheduleJob('0 0 0 * * *', exp.dailyTaskScheduler);
    this.weekTaskSchedulerID = scheduler.scheduleJob('0 0 17 * * 0', exp.weekTaskScheduler);
    //玩家分数统计 凌晨0点10分开始
    this.userScoreSchedulerID = scheduler.scheduleJob('0 0 0 * * *', exp.userScoreScheduler);

    //每隔30秒统计下联盟数据
    //this.unionUserTaskSchedulerID = scheduler.scheduleJob('20,50 * * * * *', exp.unionUserTaskScheduler);
};


//获取联盟数据
exp.unionUserTaskScheduler = async () => {

    logger.info('------------ Get Union User Data Begin ------------');
    let unionData = await dao.findData('unionModel', {
        'isDel': false,
        opening: true
    });
    for (let i = 0; i < unionData.length; i++) {
        let {
            unionID,
            ownerUid,
            ownerNickname,
            ownerAvatar,
            unionName,
            serverScore
        } = unionData[i];
        let unionInfo = {
            unionID,
            ownerUid,
            ownerNickname,
            ownerAvatar,
            unionName,
            serverScore
        };
        //保存联盟下面所有用户信息
        let allUser = await dao.findData('userModel', {
            unionInfo: {
                $elemMatch: {
                    unionID: unionID
                }
            }
        });
        let allUserList = [];
        for (let k = 0; k < allUser.length; k++) {
            let userData = allUser[k];
            // 判断是否在联盟中
            let userUnionInfoItem = userData.unionInfo.find(function (element) {
                return element.unionID === unionID;
            });
            //用户基础信息
            let {
                uid,
                nickname,
                avatar,
                isAgent,
                userType,
                isTest
            } = userData;
            //联盟基础信息

            let {
                spreaderID,
                score,
                saveScore,
                showFixScore,
                partner,
                rebateRate,
                manager,
                limitScore,
                targetScore,
                floatScore
            } = userUnionInfoItem;
            let userInfo = {
                uid,
                score,
                saveScore,
                nickname,
                avatar,
                isAgent,
                userType,
                isTest,
                spreaderID,
                showFixScore,
                partner,
                rebateRate,
                manager,
                limitScore,
                targetScore,
                floatScore
            };
            allUserList.push(userInfo);
        }
        //保存所有用户信息
        await redis.setValue('UNION_' + unionID, JSON.stringify(allUserList), 120);
    }


    logger.info('------------ Get Union User Data End   ------------');
};


exp.userScoreScheduler = async function () {

    let curLogger = require('pomelo-logger').getLogger('userScore');
    curLogger.info('[userScore] -------------------- user score count begin -------------------- ');




    // 删除7天前的游戏分数记录
    {
        let beginDay = moment().add(-7, 'd').format("YYYYMMDD");
        let matchData = { dayTime: { "$lte": beginDay } };
        dao.deleteData("userScoreModel", matchData).catch(function (err) {
            curLogger.error('dailyTaskSchedulerClearData userScoreModel err:' + err);
        });
        curLogger.info(`[userScore] delete history data beginDay = ${beginDay}`);
    }

    let yesterDay = moment().add(-1, 'd').format('YYYYMMDD');
    curLogger.info(`[userScore] count user score dayTime  = ${yesterDay}`);

    let unionData = await commonDao.findData('unionModel', { 'isDel': false });

    async.mapSeries(unionData, async (curData, cb) => {
        let unionID = curData.unionID;
        let count = await userInfoServices.reCountUserScore(unionID, yesterDay);
        curLogger.info(`[userScore] unionID = ${unionID} begin count score totoalUser = ${count} `);

        //保存营收数据
        let dateTime = moment().format('YYYY-MM-DD');
        let createTime = moment().format('x');
        await commonDao.findOneAndUpdateEx('teamDataModel', { unionID, dateTime }, { unionID, dateTime, createTime, userCount: 0, drawCount: 0, drawTotalCount: 0, diamondCount: 0 }, { new: true, upsert: true });
        cb(null);
    },
        function (err, result) {
            curLogger.info(`[userScore] -------------------- user score count end --------------------`);
        });

}



exp.beforeShutdown = async function (cb) {
    scheduler.cancelJob(this.dailyTaskSchedulerID);
    scheduler.cancelJob(this.weekTaskSchedulerID);
    scheduler.cancelJob(this.userScoreSchedulerID);
    scheduler.cancelJob(this.unionUserTaskSchedulerID);
    await dao.updateAllData("userModel", { $or: [{ roomID: { $ne: "" } }, { frontendId: { $ne: "" } }] }, { roomID: "", frontendId: "" });
    cb();
};

exp.dailyTaskScheduler = function () {


    let curLogger = require('pomelo-logger').getLogger('userScore');
    curLogger.info('dailyTaskSchedulerClearData');

    //胜率控制
    {
         dao.updateAllData('userTargetModel', {}, { endTime: "", curBureau: 0, endScore: 0, detail: [] });
         curLogger.info(`[dailyTaskScheduler] update userTargetModel`);
    }

    //玩家战绩
    {
        let beginDay = moment().add(-7, 'd').format("YYYYMMDD");
        let matchData = { dayTime: { "$lte": beginDay } };
        dao.deleteData("userScoreDataModel", matchData).catch(function (err) {
            curLogger.error('dailyTaskSchedulerClearData userScoreDataModel err:' + err);
        });
        curLogger.info(`[userScoreDataModel] delete history data beginDay = ${beginDay}`);
    }

    //钻石
    {
        let matchData = { createTime: { "$lte": Date.now() - 7 * 24 * 60 * 60 * 1000 } };
        dao.deleteData("userPayModel", matchData).catch(function (err) { logger.error('dailyTaskSchedulerClearData userPayModel err:' + err); });
    }

    //支付详情
    {
        let matchData = {
            createTime: { "$lte": Date.now() - 7 * 24 * 60 * 60 * 1000 }
        };
        dao.deleteData("userPayDetailModel", matchData).catch(function (err) {
            logger.error('dailyTaskSchedulerClearData userPayDetailModel err:' + err);
        });
    }

    //删除订单
    {
        let matchData = {
            createTime: { "$lte": Date.now() - 14 * 24 * 60 * 60 * 1000 }
        };
        dao.deleteData("orderModel", matchData).catch(function (err) {
            logger.error('dailyTaskSchedulerClearData orderModel err:' + err);
        });
    }

    // 删除7天前的游戏记录
    {
        let matchData = { createTime: { "$lte": Date.now() - 7 * 24 * 60 * 60 * 1000 } };
        dao.deleteData("userGameRecordModel", matchData).catch(function (err) {
            logger.error('dailyTaskSchedulerClearData userGameRecordModel err:' + err);
        });
    }

    //删除日志
    {
        let matchData = { createTime: { "$lte": Date.now() - 7 * 24 * 60 * 60 * 1000 } };
        dao.deleteData("userDelModel", matchData).catch(function (err) {
            logger.error('dailyTaskSchedulerClearData userDelModel err:' + err);
        });
    }

};

// 清理每周的总局数
exp.weekTaskScheduler = function () {
    logger.info('weekTaskSchedulerClearData');
    dao.updateAllData("userModel", {
        "unionInfo.weekDraw": {
            '$exists': true
        }
    }, {
        "unionInfo.$.weekDraw": 0
    }).catch(e => {
        logger.error(e.stack)
    });
    logger.info('weekTaskScheduler close');
};